import multiprocessing
import threading


def test_do(x):
    print(f"Processing item: {x}")


def multiwork(object_, n, k, do):
    """
    按照指定进程数、线程数对可迭代对象进行划分并执行相应操作
    :param object_: 可迭代对象，例如列表
    :param n: 进程数
    :param k: 线程数
    :param do: 要执行的函数对象
    """
    length = len(object_)
    part_size = length // n
    processes = []
    for i in range(n):
        start_index = i * part_size
        end_index = (i + 1) * part_size if i!= n - 1 else length
        part_data = object_[start_index:end_index]

        p = multiprocessing.Process(target=worker, args=(part_data, k, do))
        p.start()
        processes.append(p)

    for p in processes:
        p.join()


def worker(part_data, k, do):
    """
    进程中执行的函数，用于启动多个线程来处理划分的数据块
    :param part_data: 划分给该进程的数据块
    :param k: 线程数
    :param do: 要执行的函数对象
    """
    threads = []
    length = len(part_data)
    for i in range(0, length, k):
        end_index = min(i + k, length)
        for j in range(i, end_index):
            t = threading.Thread(target=do, args=(part_data[j],))
            t.start()
            threads.append(t)

    for t in threads:
        t.join()


if __name__ == "__main__":
    test_object = ["dadwad","gsdfsgdg","uisjfhdjf","ioejfkdsfn"]
    multiwork(test_object, 4, 1, test_do)